package com.tjc.eventbus;

import com.tjc.eventbus.core.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: tjc
 * @description
 * @Date Created in 21:24 2022-01-12
 */
public class SimpleServer implements Server {

    List<Listener> listeners = new ArrayList<>();

    EventPublisher eventPublisher;

    @Override
    public void init() {
        eventPublisher.publishEvent(new BeforeInitEvent());
        eventPublisher.publishEvent(new AfterInitEvent());

    }

    @Override
    public void start() {

    }

    @Override
    public void stop() {
    }

    @Override
    public void addListener(Listener listener) {
        listeners.add(listener);
        if(eventPublisher != null) {
            eventPublisher.registerListener(listener);
        }
    }

    @Override
    public void addEventPublisher(EventPublisher publisher) {
        this.eventPublisher = publisher;
        listeners.stream().forEach(publisher::registerListener);
    }

    public static void main(String[] args) {
        Listener listener = event -> {
            System.out.println("监听初始化before...");
        };
        DefaultEventPublisher publisher = new DefaultEventPublisher();
        Server server = new SimpleServer();
        server.addListener(listener);
        server.addEventPublisher(publisher);
        server.init();
        server.start();
        server.stop();
    }
}
